package com.boc.ewr.work.aspect;

import com.boc.ewr.util.file.enumeration.ImportEnum;
import com.boc.ewr.work.entity.WorkOprateRecord;
import com.boc.ewr.work.service.IWorkOprateRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.dao.DataAccessException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysDepartModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author : Wzz
 * @create : 2023-06- 19- 16:45
 * @desc : 批量导入监控切面
 */
@Aspect
@Component
@Slf4j
public class WorkOprateRecordBcimpAspect {

    @Autowired
    private IWorkOprateRecordService workOprateRecordService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    // 导入（批量导入）
    @Around("execution(* com..BatchImportController.add(..))")
    public Object logMethodCall(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法开始时间
        long startTime = System.currentTimeMillis();
        // 继续执行被拦截的方法
        Object proceed = joinPoint.proceed();
        // 获取调用类名、方法名
        StringBuilder fncNm = new StringBuilder();
        fncNm.append("批量导入-");
        // 获取批量导入方法的第一个参数 HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) joinPoint.getArgs()[0];
        // 获取导入文件名称
        String businessType = request.getParameter("businessType");
        ImportEnum businessEnum = ImportEnum.getByIndex(businessType);
        fncNm.append(businessEnum.getTypeCN());
        // 获取方法结束时间
        long endTime = System.currentTimeMillis();
        // 插入调用信息到数据库
        WorkOprateRecord workData = new WorkOprateRecord();
        LoginUser loginUser = this.getLoginUser();
        SysDepartModel sysDepartModel = sysBaseAPI.selectAllById(loginUser.getOrgCode());
        workData.setParentBranchNo(sysDepartModel.getParentId());
        workData.setOrgNo(sysDepartModel.getOrgCode());
        workData.setOrgNm(sysDepartModel.getDepartName());
        workData.setEhrTlrNo(sysBaseAPI.getWorkNoByLoginUser(loginUser));
        workData.setEmpNm(loginUser.getRealname());
        workData.setFncNm(fncNm.toString());
        workData.setStartTime(new Date(startTime));
        workData.setEndTime(new Date(endTime));

        workOprateRecordService.save(workData);

        log.info("检测到批量导入行为，正在计入工作日志...");
        return proceed;
    }

    // 获取登录用户
    private LoginUser getLoginUser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser;
    }
}
